package com.trendytech.tds.base.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.trendytech.tds.common.chart.ChartData;
import com.trendytech.tds.entity.MonitorItemValueReal;
import com.trendytech.tds.entity.SystemAlertVO;

public class BaseController {

	protected Log log = LogFactory.getLog(this.getClass());

	protected static final String DATA = "data";
	protected static final String RESULT = "result";
	protected static final String SUCCESS = "success";
	protected static final String FAILURE = "failure";
	protected static final String MESSAGE = "message";

	protected static final String PAGER = "pager";
	protected static final String CONTENT = "content";
	protected static final String TITLE = "title";
	protected static final String MAIN_VIEW = "/common/portal";
	protected static final String LIST = "list";
	protected static final String ALARM = "alarm";
	protected static final String NO_AUTH = "noAuth";
	
	protected static final String ATTR_USER = "user";
	
	protected static final String DAYS="days ago";
	protected static final String HOURS="hours ago";
	protected static final String MINUTES="minutes ago";
/*	@Autowired
	protected IResourceService resService;
	@Autowired
	protected ISystemAlertService systemAlertService;*/
	
	@ExceptionHandler
	public ModelAndView exp(HttpServletRequest request, Exception ex) {
		ModelMap map = new ModelMap();
		map.put("msg", ex.getMessage());
		map.put("stack", ex.getStackTrace());
		
		if (isAjaxRequest(request)) {
			return new ModelAndView("error/error-ajax", map);
		} else if (ex.getMessage().equals(NO_AUTH)) {
			return new ModelAndView("error/noauth", map);
		} else {
			return new ModelAndView("error/error", map);
			
		}
	}
	
	protected boolean isAjaxRequest(HttpServletRequest request){
		return ("XMLHttpRequest".equalsIgnoreCase(request
				.getHeader("X-Requested-With"))) ;
	}
	
	/**
	 * Get the main view
	 * 
	 * @param request
	 * @param title
	 * @param viewName
	 * @param map
	 * @return
	 */
	protected ModelAndView view(HttpServletRequest request, String title, String viewName, ModelMap map) {

		//setContent(request, title, viewName);
		setAttributes(request);
		return new ModelAndView(MAIN_VIEW, map);
	}

	/**
	 * Set page title and content view
	 * 获取警告信息
	 * @param request
	 * @param title
	 * @param content
	 */
/*	protected void setContent(HttpServletRequest request, String title, String content) {
		request.setAttribute(TITLE, title);
		request.setAttribute(CONTENT, content);
		List<SystemAlertVO> list=systemAlertService.getCountAndType();
		Date date=new Date();
		int alertCount=0;
		for (SystemAlertVO systemAlertVO : list) {
			long time=date.getTime()-systemAlertVO.getCreateTime().getTime();
			time=time/(1000*60);
			if (time<60){
				systemAlertVO.setTime(time);
				systemAlertVO.setTimeType(MINUTES);
			}else if(time>=60&&time<(24*60)){
				systemAlertVO.setTime(time/60);
				systemAlertVO.setTimeType(HOURS);
			}else{
				systemAlertVO.setTime(time/(60*24));
				systemAlertVO.setTimeType(DAYS);
			}
			alertCount=alertCount+systemAlertVO.getCount();
		}
		request.setAttribute("alertCount",alertCount);
		request.setAttribute(ALARM, list);
	}*/

	/**
	 * 非ajax请求时设置菜单
	 * @param request
	 */
	protected void setAttributes(HttpServletRequest request) {

/*		List<Resource> topList = null;
		Resource currentRes = null;
		// 当前用户信息
		UserInfo user = (UserInfo) request.getAttribute(ATTR_USER);
		// 当前请求地址
		String requri = request.getServletPath();

		if (!resService.hasAuth(user.getId(), requri)) {
			try {
				throw new Exception(NO_AUTH);
			} catch (Exception e) {
				log.error(e);
			}
		}
		
		// 获取顶部导航菜单列表
		topList = resService.getTopByUserId(user.getId());
		// 当前请求资源信息
		currentRes = resService.getByUrl(requri);

		if (currentRes != null) {
			if (currentRes.getCategory() == Resource.Category.menu.ordinal()) {
				// 获取菜单下的按钮
				List<Resource> buttons = resService.getButtons(user.getId(),
						currentRes.getId());
				request.setAttribute("buttons", buttons);
			}
			for (Resource top : topList) {
				// 获取当前顶部菜单下的子菜单
				if (top.getId().equals(currentRes.getTopId())) {
					List<Resource> subList = null;
					// 当前顶部菜单下的二级菜单列表
					subList = resService.getSubByUserId(user.getId(), top.getId());

					// 设置顶部菜单为当前菜单
					top.setCurMenu(true);

					for (Resource sub : subList) {
						// 三级菜单列表
						List<Resource> thirdList = null;
						thirdList = resService.getSubByUserId(user.getId(), sub.getId());
						sub.setChildren(thirdList);
					}
					request.setAttribute("menuList", subList); // 菜单列表
					break;
				}
			}

			request.setAttribute("currentMenu", currentRes); // 当前菜单
			request.setAttribute("topList", topList); // 顶部导航菜单列表
		} else {
			// 表单链接
			String url = recoverResouresUrl(request);
			// 当前请求资源信息
			currentRes = resService.getByUrl(url);
			if (currentRes != null) {
				request.setAttribute("currentMenu", currentRes); // 当前菜单
			}
		}*/
	}
	
	/**
	 * 带参数的url转换成{id}形式（与数据库中url一致）
	 * @param request
	 * @return
	 */
	private String recoverResouresUrl(HttpServletRequest request){
		String path = request.getServletPath();
		String query = request.getQueryString();
		if(query != null){
			Pattern p = Pattern.compile(".*=([^&]{32}).*");
			Matcher m = p.matcher(query);
			if(m.matches()){
				query = query.replace(m.group(1), "{id}");
			}
		}
		return query != null ? path + "?" + query : path;
	}

	/**
	 * 封装图表数据
	 * @param seriesNameList 监控对象列表
	 * @param itemValueList 指定类型的监控对象的指定性能数据，如所有pool的read性能数据
	 * @return
	 */
	public Map<String, Object> returnChartData(List<String> seriesNameList
			, List<MonitorItemValueReal> itemValueList) {
		// 返回结果
		Map<String, Object> resultMap = new HashMap<String, Object>();
		// 返回结果——性能数据
		List<ChartData> dataset = new ArrayList<ChartData>();
		// 横坐标值
		List<String> xAxisList = new ArrayList<String>();
		// 格式化横坐标值
		SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
		
		long time = System.currentTimeMillis();
		// 封装每个监控对象的性能数据
		for (int i = 0; i < seriesNameList.size(); i++) {
			// 监控对象名称
			String name = seriesNameList.get(i);
			// 监控对象性能数据
			List<Double> valueList = new ArrayList<Double>();
			for (MonitorItemValueReal itemValue : itemValueList) {
				String objName = itemValue.getObjectName();
				if (name.equals(objName)) {
					valueList.add(itemValue.getItemValue());
				} else {
					continue;
				}
				if (i == 0) {
					// 横坐标时间
					xAxisList.add(sdf.format(itemValue.getCreateTime()));
				}
			}
			// 图表数据实体
			ChartData data = new ChartData();
			data.setName(name);
			data.setData(valueList);
			dataset.add(data);
		}
		if (log.isDebugEnabled()) {
			log.debug("cost>>>>>" + (System.currentTimeMillis() - time));
		}
		
		resultMap.put("categories", xAxisList);
		resultMap.put("dataset", dataset);
		
		return resultMap;
	}
	
}
